<?php
/**
 * Created by PhpStorm.
 * User: william
 * Date: 16-8-31
 * Time: 下午2:44
 */
namespace V1;
class C_ProductList extends \ResourceClass {
    public $isActive = true;
    public $remark = '获取产品列表';
    public function get(array $req, array $post, &$result)
    {
        if (!isset($req['uid'])) {
            return 'require user id ';
        }
        if (!isset($req['userType'])) {
            return 'require user type';
        }
        if (!isset($req['k']) || !isset($req['t'])) {
            return 'data error';
        }
        if (!isset($req['enterpriseId'])) {
            return 'require enterprise id';
        }
        if (\Biz\UserHandler::checkAuth($req['userType'],$req['uid'],$req['enterpriseId'],$req['t'],$req['k']) == false) {
            return 'data illegal';
        }
        if (!isset($req['channelId'])) {
            return 'require channel id';
        }
        $l = isset($req['l']) ? $req['l'] : 100000;
        $o = isset($req['o']) ? $req['o'] : 0;
        try {
            $customer_handler = new \Biz\UserHandler();
            $customer_cls = $customer_handler ->getById($req['userType'],$req['uid']);
            if(!is_object($customer_cls) && $customer_cls->getEnterpriseId() ==false){
                return 'data error';
            }
            $channel_id = $customer_cls ->getChannelId();
            $enterprise_id = $customer_cls ->getEnterpriseId();
            if ($channel_id != $req['channelId']) {    //验证用户渠道
                return 'invalid channel id ';
            }
            if ($enterprise_id != $req['enterpriseId']) {//验证用户企业
                return 'invalid enterprise id ';
            }
            $name ='';
            $brand_id ='';
            if(isset($req['name'])) {
                $name = $req['name'];
            }
            if (isset($req['brandId'])) {
                $brand_id = $req['brandId'];
            }
            //过滤产品渠道中商品issale=0
            $product_channel_handler = new \Biz\ProductHandler();
            $product_channel_lists = $product_channel_handler->getProductChannelByChannelId($channel_id);
            foreach($product_channel_lists as $product_channel_cls){
                $product_ids[] = $product_channel_cls['product_id'];
            }
            // 实例化列表类
            $tabulation = new \Cls\Tabulation();
            // 初始化列表类相关参数
            $tabulation->setWhere('enterprise_id', $req['enterpriseId'])
                ->setOffset($o)
                ->setLimit($l);
            if(!empty($product_ids)){
                $tabulation->setWhere('id', 'in',$product_ids);
            }
            if(!empty($name)){
                $tabulation->setWhere('name', $name);
            }
            if(!empty($brand_id) && $brand_id == 0 ){
                $tabulation->setWhere('brand_id', $brand_id);
            }
            $product_handler = new \Biz\ProductHandler();
            $product_handler::getProductListsByEnterpriseId($tabulation);
            $total = $tabulation->getTotal();
            // 获取当前渠道信息
            $channel_cls = \Biz\ChannelHandler::getChannelById($channel_id);
            $discount = $channel_cls->getDiscount();
            $temp = array();
            /**
             * @var \Cls\Product\Product $product_cls
             */
            foreach($tabulation->getData() as $key=>$product_cls){
                $tmp_product = array();
                $tmp_product['id'] = $product_cls->getId();
                $tmp_product['enterprise_id'] = $product_cls->getEnterpriseId();
                $tmp_product['brand_id'] = $product_cls->getBrandId();
                $tmp_product['name'] = $product_cls->getName();
                $tmp_product['icon_url'] = $product_cls->dealIconUrl();
                $tmp_product['repertory_warning'] = $product_cls->getStockWarning();
                $tmp_product['individual_packing'] = $product_cls->getSellUnitString(); // 老版本
                $tmp_product['mass_packing'] = $product_cls->getSellUnitString(); // 老版本
                $tmp_product['sell_unit_string'] = $product_cls->getSellUnitString();
                $tmp_product['remark'] = $product_cls->getDescription();
                $tmp_product['insert_time'] = $product_cls->getCreateTime();
                $tmp_product['is_del'] = $product_cls->getDelStatus();
                $tmp_product['brandname'] = $product_cls->getBrandInfo()->getName();
                $product_channel_handler = new \Biz\ProductHandler();
                $product_channel_cls=$product_channel_handler->getChannelProductByChannelIdAndProductId($channel_id,$product_cls->getId());
                $channel_price = $product_channel_cls->getPriceRange();
                if($channel_price !=false ){
                    $tmp_product['channel_price'] = (string)$channel_price;
                }else{
                    $tmp_product['channel_price'] ='';
                }
                $brand_handler = new \Biz\BrandHandler();
                $brand_cls = $brand_handler->getBaseBrandByBrandPidAndEnterpriseId($product_cls->getEnterpriseId(),$product_cls->getBrandInfo()->getPid());
                if(!is_object($brand_cls)){
                    continue;
                }
                $tmp_product['parent_brand_name'] = $brand_cls->getName();
                $tmp_product['parent_brand_id'] = $brand_cls->getId();
                $tmp_product['collect_stock'] = 0;
                if(is_object($product_cls) && $product_cls->getSkuList() != false){
                    foreach ($product_cls->getSkuList() as $sku) {
                        $tmp_product['collect_stock'] += $sku->getStock(); //累加库存信息
                        $tmp_product['stock_warning'] = ($tmp_product['collect_stock'] >= $product_cls->getStockWarning()) ? 0 : 1 ; //是否库存预警
                        if (trim($sku->getAttr()) == 'a:0:{}') {
                            $sku->setAttr('【统一属性】');
                        } else {
                            $tmp_attr = unserialize(trim($sku->getAttr()));
                            $tmp_attr_str = '';
                            if (is_array($tmp_attr)) {
                                foreach ($tmp_attr as $name=>$attr) {
                                    $tmp_attr_str .= $name.':'.$attr.',';
                                }
                            }
                            $sku->setAttr(substr($tmp_attr_str,0,-1));
                        }
                        $tmp_sku = array(
                            'id' =>$sku->getId(),
                            'product_id' =>$sku->getProductId(),
                            'imgurl' =>$sku->getImageUrl(),
                            'attr' =>$sku->getAttr(),
                            'code' =>$sku->getCode(),
                            'sellprice' =>$sku->getSellingPrice()*$discount,
                            'cost' =>$sku->getCost(),
                            'stock' =>$sku->getStock(),
                            'insert_time' =>$sku->getCreateTime(),
                            'update_time' =>$sku->getUpdateTime(),
                        );
                        $tmp_product['sku_info'][] =$tmp_sku;
                    }
                }
                $temp[] = $tmp_product;
            }
            $result['product_list'] =$temp;
            /*
            *  促销活动信息
            *  ①筛选该企业下的所有有效活动
            *  ②在活动中筛选出用户所在渠道的活动，即活动的渠道为所有活动或者参与渠道中包含该渠道即可
            *  ③把满足条件的活动参与的产品与查询出的产品对应起来
            *  ④返回活动信息
            */
            if ($tabulation->getSuccessStatus()) {
                $market_biz = new \Biz\MarketHandler();
                $tabulation = new \Cls\Tabulation();
                $time = date('Y-m-d H:i:s',time());
                // 初始化列表类相关参数
                $tabulation->setLimit(99999)
                    ->setWhere('enterprise_id',$enterprise_id)
                    ->setWhere('end_time', '>', $time)
                    ->setOrderBy('create_time','DESC');
                $market_biz->getListByEnterpriseId($tabulation);
                if($tabulation->getSuccessStatus()){
                    $market_list = $tabulation->getData();
                    //营销活动的渠道信息
                    $market_biz->completeChannelListByMarketList($market_list);
                    //完善营销活动中的商品信息
                    $market_biz->completeProductListByMarketProductList($market_list);
                    /**
                     * @var $market_cls \Cls\Market\Market
                     */
                    foreach ($market_list as $market_cls) {
                        //如果活动参与的渠道类型是所有渠道或者当前用户所在的渠道在参与活动的渠道中
                        if ($market_cls->getChannelType() == \Cls\Market\Market::CHANNEL_ALL || $market_cls->judgeInChannel($channel_id)) {
                            //获取该活动参与的所有产品
                            $market_product_list = $market_cls->getProductList();
                            //取出所有产品的id组成id集合
                            $product_ids = array();
                            /**
                             * @var $market_product_cls \Cls\Market\Product
                             */
                            foreach ($market_product_list as $market_product_cls) {
                                $product_ids[] = $market_product_cls->getProductId();
                            }
                            //如果参与活动产品类型为所有产品或者该产品在参与的活动中
                            foreach ($result['product_list'] as $key => $product) {
                                $result['product_list'][$key]['activity_info'] = isset($result['product_list'][$key]['activity_info']) ? $result['product_list'][$key]['activity_info'] : array();
                                if ($market_cls->getProductType() == \Cls\Market\Market::PRODUCT_ALL || in_array($product['id'], $product_ids)) {
                                    $market_temp['id'] = $market_cls->getId();
                                    $market_temp['title'] = $market_cls->getTitle();
                                    $market_temp['type'] = $market_cls->getType();
                                    $market_temp['condition'] = $market_cls->getCondition();
                                    $market_temp['discount'] = $market_cls->getDicount();
                                    $market_temp['rewards'] = $market_cls->getRewards();
                                    $market_temp['product_type'] = $market_cls->getProductType();
                                    $market_temp['channel_type'] = $market_cls->getChannelType();
                                    $market_temp['start_time'] = $market_cls->getStartTime();
                                    $market_temp['end_time'] = $market_cls->getEndTime();
                                    $market_temp['status'] = $market_cls->getStatus();
                                    $market_temp['enterprise_id'] = $market_cls->getEnterpriseId();
                                    $market_temp['unit'] = $market_cls->getUnit();
                                    $market_temp['create_time'] = $market_cls->getCreateAt();
                                    $market_temp['edit_time'] = $market_cls->getUpdateAt();
                                    $market_temp['update_time'] = $market_cls->getUpdateAt();
                                    $result['product_list'][$key]['activity_info'][] = $market_temp;
                                }
                            }
                        }
                    }
                    //计算折扣  按折扣活动的更新时间为键
                    foreach ($result['product_list'] as $k => $product) {
                        if (isset($product['activity_info'])&&!empty($product['activity_info'])) {
                            $new_activity = array();
                            foreach ($product['activity_info'] as $key => $activity) {
                                if ($activity['type']  == 3) {
                                    $time = strtotime($activity['update_time']);
                                    $new_activity[$time] = $activity;
                                    //因为后面需要重新筛选折扣活动，所以需要把原先的折扣活动删除
                                    unset($result['product_list'][$k]['activity_info'][$key]);
                                }
                            }
                            $new_activity = isset($new_activity) ? $new_activity : array();
                            krsort($new_activity);//把最新的折扣活动放前面
                            $sort_activity = current($new_activity);//取出最终满足的活动
                            if(!empty($sort_activity)) {
                                foreach($product['sku_info'] as $ke => $sku_cls){
                                    $result['product_list'][$k]['sku_info'][$ke]['sellprice'] = round($sku_cls['sellprice']*$sort_activity['discount'],2);
                                }
                                array_push($result['product_list'][$k]['activity_info'],$sort_activity);
                            }
                        }else{
                            $result['product_list'][$k]['activity_info'] = array();
                        }
                        $activity_info = array_merge($result['product_list'][$k]['activity_info']);
                        $result['product_list'][$k]['activity_info'] = $activity_info;
                    }
                } else {
                    foreach ($result['product_list'] as $key => $product) {
                        $result['product_list'][$key]['activity_info'] = array();
                    }
                }
            }
            $result['product_list'] = $this->makeOnsaleItems($result['product_list']);
            $result['total'] = $total;
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }

    private function makeOnsaleItems($items)
    {
        $product_list = array();
        foreach ($items as $key=>$item) {
            $product_list[] = $item;
            if (isset($item['activity_info'])) {
                if (count($item['activity_info'])) {
                    $product_list[$key]['brand_id'] = 0;
                    $product_list[$key]['brandname'] = '特价促';
                    $product_list[$key]['parent_brand_id'] = 0;
                    $product_list[$key]['parent_brand_name'] = '特价促';
                }
            }
        }

        // 按brand升序排序
        $brand_ids = array();
        foreach ($product_list as $product) {
            $brand_ids[] = $product['brand_id'];
        }
        array_multisort($brand_ids, SORT_ASC, $product_list);
        return $product_list;
    }
}